package com.myjoje.service.system;

import com.myjoje.base.BaseService;
import com.myjoje.bean.system.MenuBean;
import com.myjoje.bean.system.MenuRoleBean;
import com.myjoje.dao.system.MenuDao;
import com.myjoje.jpa.MenuJpa;
import com.myjoje.jpa.MenuRoleJpa;
import com.myjoje.util.Message;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuService extends BaseService {

    @Autowired
    private MenuJpa menuJpa;

    @Autowired
    private MenuRoleJpa menuRoleJpa;

    @Autowired
    private MenuDao menuDao;


    /**
     * 保存或更新菜单
     */
    public Message saveOrUpdateMenu(MenuBean bean) {
        String id = bean.getId();
        if (isEmpty(id)) {
            return saveMenu(bean);
        } else {
            return updateMenu(bean);
        }
    }

    /**
     * 更新菜单
     */
    private Message updateMenu(MenuBean bean) {
        String id = bean.getId();
        MenuBean oldBean = menuJpa.getOne(id);
        String name = bean.getName();
        if (isEmpty(name)) {
            return Message.error("菜单名不能为空");
        }
        String oldName = oldBean.getName();
        if (name.equals(oldName)
                && bean.getIcon().equals(oldBean.getIcon())
                && bean.getPriority().equals(oldBean.getPriority())
                && bean.getStatus().equals(oldBean.getStatus())
                && bean.getUrl().equals(oldBean.getUrl())) {
            return Message.error("请修改后提交");
        }
        if (!name.equals(oldName)) {
            //如果是一级菜单验证菜单名不重复
            if (!validateOneLevelMenuName(bean)) {
                return Message.error("菜单名称已经存在");
            }
        }
        bean.setModifyTime(getDateTime());
        bean.setModifyUser(getCurrentUserId());
        menuJpa.save(bean);
        return Message.success("更新成功");
    }

    /**
     * 保存菜单，只验证一级菜单不能重复
     */
    private Message saveMenu(MenuBean bean) {
        if (isEmpty(bean.getName())) {
            return Message.error("菜单名不能为空");
        }
        if (!validateOneLevelMenuName(bean)) {
            return Message.error("菜单名称已经存在");
        }
        bean.setCreateTime(getDateTime());
        bean.setCreateUser(getCurrentUserId());
        menuJpa.save(bean);
        return Message.success("保存成功");
    }

    private Boolean validateOneLevelMenuName(MenuBean bean) {
        //一级菜单
        if (isEmpty(bean.getParentId())) {
            Map map = getMap("parentId", null);
            map.put("name", bean.getName());
            Long count = menuDao.getCount(map);
            if (count > 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取菜单分页数据
     */
    public List<MenuBean> getMenuList(String sContent, Integer currentPage, Integer pageSize) {
        Map map = getMap("sContent", sContent);
        map.put("parentId", null);
        List<MenuBean> list = menuDao.get(currentPage, pageSize, map);
        list.forEach(bean -> getMenuByParentId(bean));
        return list;
    }

    /**
     * 获取菜单分页数据
     */
    public Long getMenuCount(String sContent) {
        Map map = getMap("sContent", sContent);
        map.put("parentId", null);
        return menuDao.getCount(map);
    }

    /**
     * 根据父id获取菜单
     *
     * @param bean
     */
    private void getMenuByParentId(MenuBean bean) {
        getMenuByParentId(bean, null);
    }

    private void getMenuByParentId(MenuBean bean, Set menuIds) {
        Map map = getMap("parentId", bean.getId());
        if (null != menuIds && menuIds.size() > 0) {
            map.put("status", MenuBean.STATUS_SHOW);
            List<MenuBean> children = menuDao.get(null, null, map);
            //过滤
            List<MenuBean> list = new ArrayList<>();
            children.forEach(child -> {
                String menuId = child.getId();
                if (menuIds.contains(menuId)) {
                    list.add(child);
                }
            });
            bean.setChildren(list);
            list.forEach(menu -> getMenuByParentId(menu, menuIds));
        } else {
            List<MenuBean> children = menuDao.get(null, null, map);
            if (children.size() > 0) {
                bean.setChildren(children);
                children.forEach(menu -> getMenuByParentId(menu));
            } else {
                bean.setChildren(new ArrayList<>());
            }
        }
    }


    /**
     * 删除菜单
     */
    public Object deleteMenu(String id) {
        menuJpa.deleteById(id);
        return Message.success("删除成功");
    }

    /**
     * 获取菜单树形结构
     *
     * @return
     */
    public Message getMenuTree() {
        Map map = getMap("status", "1");
        map.put("parentId", null);
        List<MenuBean> list = menuDao.get(null, null, map);
        list.forEach(bean -> getMenuByParentId(bean));
        return Message.success("请求成功", list);
    }

    /**
     * 根据角色获取菜单
     */
    public Message getMenuIdsByRole(String roleId) {
        MenuRoleBean bean = menuRoleJpa.findByRoleId(roleId);
        if (null != bean) {
            String menuIds = bean.getMenuIds();
            if (isNotEmpty(menuIds)) {
                return Message.success("获取成功", menuIds.split(","));
            }
        }
        return Message.success("获取成功", new ArrayList<>());
    }

    /**
     * 保存菜单角色对应关系
     */
    public Object saveMenuRole(String roleId, String menuIds) {
        MenuRoleBean bean = menuRoleJpa.findByRoleId(roleId);
        if (null == bean) {
            bean = new MenuRoleBean();
            bean.setRoleId(roleId);
            bean.setCreateTime(getDateTime());
            bean.setCreateUser(getCurrentUserId());
        } else {
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
        }
        bean.setMenuIds(menuIds);
        menuRoleJpa.save(bean);
        return Message.success("更新成功");
    }

    /**
     * 根据角色id获取菜单
     *
     * @param roleIds
     * @return
     */
    public List<MenuBean> getMenuByRoleIds(String roleIds) {
        //使用set去除重复id
        Set set = new HashSet();
        List<String> roleList = Arrays.asList(roleIds.split(","));
        //循环角色,去除重复id
        roleList.forEach(roleId -> {
            //获取角色对应的裁断ids
            MenuRoleBean bean = menuRoleJpa.findByRoleId(roleId);
            String menuIds = bean.getMenuIds();
            if (isNotEmpty(menuIds)) {
                List<String> menuIdList = Arrays.asList(menuIds.split(","));
                menuIdList.forEach(menuId -> set.add(menuId));
            }
        });

        //处理子节点没全选，没有父id情况
        List<String> parentIds = menuDao.getMenuParentId(set);
        parentIds.stream()
                .filter(parentId -> isNotEmpty(parentId))
                .distinct()
                .collect(Collectors.toList())
                .forEach(parentId -> set.add(parentId));

        //获取显示的一级菜单
        Map map = getMap("menuIds", set);
        map.put("parentId", null);
        map.put("status", MenuBean.STATUS_SHOW);
        List<MenuBean> list = menuDao.get(null, null, map);
        list.forEach(menu -> getMenuByParentId(menu, set));

        return list;
    }


}
